#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_libxml2_fun_006.py
@Time:      2024/02/23 11:12:50
@Author:    hongfeng
@Version:   1.0
@Contact:   wb-zhf668260@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    hongfeng
"""

import os
from common.basetest import LocalTest
class Test(LocalTest):
    """
    See tc_libxml2_fun_006.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "libxml2-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > parse_html.c <<EOF
#include <stdio.h>
#include <libxml/HTMLparser.h>
#include <libxml/HTMLtree.h>

void print_element_names(xmlNode * a_node) {
    xmlNode *cur_node = NULL;

    for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
        if (cur_node->type == XML_ELEMENT_NODE) {
            printf("Element name: %s\\n", cur_node->name);
        }
        // 递归处理子节点
        print_element_names(cur_node->children);
    }
}

void parseFile(const char *filename) {
    // 初始化libxml2
    xmlInitParser();

    // 创建一个新的HTML解析器
    htmlDocPtr doc = htmlReadFile(filename, NULL, HTML_PARSE_RECOVER | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING);
    if (doc == NULL) {
        fprintf(stderr, "Failed to parse %s\\n", filename);
        return;
    }

    // 获取文档的根节点
    xmlNodePtr root_element = xmlDocGetRootElement(doc);

    // 遍历DOM树
    print_element_names(root_element);

    // 释放内存
    xmlFreeDoc(doc);
    xmlCleanupParser();
}

int main() {
    parseFile("test_006.html");

    return 0;
}
"""
        self.cmd(cmdline)
        self.cmd("gcc -o parse_html parse_html.c `xml2-config --cflags --libs`")
        file_dir = os.path.dirname(__file__)
        self.cmd(f"cp {file_dir}/test.html ./test_006.html")

    def test(self):
        ret_c,ret_o = self.cmd("./parse_html")
        self.assertTrue("Element name: html" in ret_o, 'check output error.')
        self.assertTrue("Element name: p" in ret_o, 'check output error.')
        
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm parse_html.c parse_html test_006.html")
